package utils

import (
	"encoding/binary"
	"github.com/golang/protobuf/proto"
	"github.com/pkg/errors"
	"net"
	"server5/protobuf"
)

//传输类
type Transfer struct {
	//连接
	Conn net.Conn
	//数据缓冲
	ReadBuf  []byte
	WriteBuf []byte
}

func NewTransfer(conn net.Conn) *Transfer {
	return &Transfer{
		Conn:     conn,
		ReadBuf:  make([]byte, 1024),
		WriteBuf: make([]byte, 1024),
	}
}

func (t *Transfer) ReadPkg() (msg protobuf.Msg, err error) {
	//读取数据长度
	n, err := t.Conn.Read(t.ReadBuf[:4])
	if n != 4 || err != nil {
		err = errors.WithStack(err)
		return
	}
	//[]byte转换为整数
	pkgLen := binary.BigEndian.Uint32(t.ReadBuf[:4])

	//读取数据
	n, err = t.Conn.Read(t.ReadBuf[:pkgLen])
	if n != int(pkgLen) || err != nil {
		err = errors.WithStack(err)
		return
	}

	//反序列化
	err = proto.Unmarshal(t.ReadBuf[:pkgLen], &msg)
	if err != nil {
		err = errors.WithStack(err)
		return
	}

	return
}

func (t *Transfer) WritePkg(data []byte) (err error) {
	//发送数据长度
	//int转为[]byte
	binary.BigEndian.PutUint32(t.WriteBuf[:4], uint32(len(data)))
	//发送
	n, err := t.Conn.Write(t.WriteBuf[:4])
	if n != 4 || err != nil {
		err = errors.WithStack(err)
		return
	}
	//发送数据
	n, err = t.Conn.Write(data)
	if n != int(len(data)) || err != nil {
		err = errors.WithStack(err)
		return
	}
	return nil
}
